package com.erp.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.erp.dao.PrivilegeDAO;
import com.erp.dao.RoleDAO;
import com.erp.domain.TPrivilege;
import com.erp.domain.TRole;
import com.erp.dto.Page;
import com.erp.dto.Privilege;
import com.erp.dto.Role;

@Service(value = "roleService")
@Transactional
public class RoleService {

	@Resource(name = "roleDAO")
	private RoleDAO roleDAO;

	@Resource(name = "privilegeDAO")
	private PrivilegeDAO privilegeDAO;

	/**
	 * ACT_ID_*表操作接口
	 */
	@Resource(name = "identityService")
	private IdentityService identityService;

	private Integer add(Role role) {
		TRole tRole = new TRole(role);
		return (Integer) roleDAO.save(tRole);
	}

	/**
	 * 添加角色时同步到ActivitiACT_ID_GROUP表中
	 * 
	 * @param role
	 * @param synToActiviti
	 */
	public void add(Role role, boolean synToActiviti) {
		role.setId(this.add(role));
		// TODO 同步添加到Activiti
		if (synToActiviti) {
			synToActiviti(role);
		}

	}

	/**
	 * 把角色信息同步添加或更新到Activiti中
	 * 
	 * @param role
	 */
	public void synToActiviti(Role role) {
		if (role.getId() != null) {
			String roleId = role.getId().toString();
			List<Group> activitiGroups = identityService.createGroupQuery()//
					.groupId(roleId)//
					.list();//
			// TODO 判断Activiti中是否已存在该ID的用户组（角色）
			Group activitiGroup = null;
			if (activitiGroups.size() == 1) {// 若存在该角色则更新角色信息
				// 获取数据库里的用户组（角色）信息
				activitiGroup = activitiGroups.get(0);
			} else if (activitiGroups.size() == 0) {// 若不存在该角色则添加用户信息
				// 在Activiti里新建用户组（角色）
				activitiGroup = identityService.newGroup(role.getSign());
			}
			activitiGroup.setName(role.getName());
			activitiGroup.setType(role.getDescription());
			identityService.saveGroup(activitiGroup);
		}
	}

	public void delete(Role role) {
		roleDAO.deleteById(role.getId());
	}

	public Role update(Role role) {
		TRole tRole = roleDAO.getById(role.getId());
		tRole.setName(role.getName());
		tRole.setDescription(role.getDescription());
		roleDAO.update(tRole);
		return new Role(tRole);
	}

	public void update(Role role, boolean synToActiviti) {
		role = this.update(role);
		// 同步更新角色信息到Activiti
		if (synToActiviti) {
			synToActiviti(role);
		}
	}

	public void setRolePrivilege(Role role) {
		TRole tRole = roleDAO.getById(role.getId());
		List<TPrivilege> privilegeSet = new ArrayList<TPrivilege>(0);
		for (Privilege p : role.getPrivilegeList()) {
			privilegeSet.add(privilegeDAO.getById(p.getId()));
		}
		tRole.setPrivileges(privilegeSet);
		roleDAO.update(tRole);
	}

	public List<Role> listAll() {
		List<TRole> TRoleList = new ArrayList<TRole>(0);
		List<Role> roleList = new ArrayList<Role>(0);
		TRoleList = roleDAO.listAll();
		if (TRoleList != null) {
			for (int i = 0; i < TRoleList.size(); i++) {
				roleList.add(new Role(TRoleList.get(i)));
			}
		}
		return roleList;
	}

	public Role getRoleById(Integer id) {
		Role role = new Role(roleDAO.getById(id));
		return role;
	}

	public List<Privilege> getPrivilegeListByArray(Integer[] privilegeIds) {
		List<Privilege> privilegeList = new ArrayList<Privilege>(0);
		for (int i = 0; i < privilegeIds.length; i++) {
			privilegeList.add(new Privilege(privilegeDAO
					.getById(privilegeIds[i])));
		}
		return privilegeList;
	}

	public List<Role> getRoleListByArray(Integer[] roleIds) {
		List<Role> roleList = new ArrayList<Role>(0);
		for (int i = 0; i < roleIds.length; i++) {
			roleList.add(new Role(roleDAO.getById(roleIds[i])));
		}
		return roleList;
	}

	public List<Role> getPagedList(Page page) {
		// 开始页码
		int from = (page.getPageIndex() - 1) * page.getPageSize();
		List<Role> roleList = null;
		int totalRecord = roleDAO.countAll().intValue();
		page.setTotalRecord(totalRecord);
		int totalPage = 1;
		if (totalRecord > 0) {
			roleList = new ArrayList<Role>();
			List<TRole> tRoleList;
			tRoleList = roleDAO.paging(from, page.getPageSize());
			// 设置总页数
			totalPage = totalRecord % (page.getPageSize()) > 0 ? totalRecord
					/ (page.getPageSize()) + 1 : totalRecord
					/ (page.getPageSize());

			for (int i = 0; i < tRoleList.size(); i++) {
				roleList.add(new Role(tRoleList.get(i)));
			}
		}
		page.setTotalPage(totalPage);
		return roleList;
	}

}
